package com.aorise.controller.order;

import com.aorise.exception.DataValidationException;
import com.aorise.exception.SystemException;
import com.aorise.model.order.WorkOrderAddVO;
import com.aorise.model.order.WorkOrderInfo;
import com.aorise.model.order.WorkOrderModel;
import com.aorise.model.order.WorkRepairCameraVO;
import com.aorise.model.system.User;
import com.aorise.service.order.RepairCameraService;
import com.aorise.service.order.WorkOrderService;
import com.aorise.service.system.UserService;
import com.aorise.utils.*;
import com.aorise.utils.json.JsonResponseData;
import com.aorise.utils.page.Page;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author:psl
 * @Desicription: 运维工单控制器
 * @Date:Created in  2019-06-03.
 * @Modified By:
 */
@Slf4j
@RestController
@Api(description ="工单信息接口")
public class WorkOrderController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private WorkOrderService workOrderService;

    @Autowired
    private RepairCameraService repairCameraService;

    @Autowired
    private UserService userService;

    /**
     * 根据筛选条件进行分页查询运维工单信息
     * HTTP 方式：GET
     * API 路径：/api/workOrder/pageIndex/{pageIndex}/pageNum/{pageNum}
     * 方法名：getAllWorkOrderListByPage
     * 方法返回类型：String
     *
     * @Author: psl
     * @Date: 2019-06-03
     */
    @RequiresPermissions("YWGDFW")
    @ApiOperation(value = "根据筛选条件进行分页查询运维工单信息", httpMethod = "GET", response = String.class, notes = "根据筛选条件进行分页查询运维工单信息,提供运维工单管理-查询列表使用")
    @RequestMapping(value = "/api/workOrder/pageIndex/{pageIndex}/pageNum/{pageNum}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String getAllWorkOrderListByPage(@ApiParam(value = "创建日期开始", required = false) @RequestParam(value = "startCreateTime", required = false) String startCreateTime,
                                            @ApiParam(value = "创建日期结束", required = false) @RequestParam(value = "endCreateTime", required = false) String endCreateTime,
                                            @ApiParam(value = "运维人员姓名", required = false) @RequestParam(value = "reason", required = false) String maintUserName,
                                            @ApiParam(value = "是否关注 0 不关注显示全部不传，1关注", required = false) @RequestParam(value = "isFocus", required = false) String isFocus,
                                            @ApiParam(value = "工单状态：1待接单，2处理中，3退回，4待确认，5未通过，6完成", required = false) @RequestParam(value = "status", required = false) Integer wStatus,
                                            @ApiParam(value = "页索引", required = true) @PathVariable(value = "pageIndex", required = true) String pageIndex,
                                            @ApiParam(value = "页大小", required = true) @PathVariable(value = "pageNum", required = true) String pageNum) {

        logger.debug("Request RESTful API:getAllWorkOrderListByPage");
        logger.debug("startCreateTime：" + startCreateTime);
        logger.debug("endCreateTime：" + endCreateTime);
        logger.debug("maintUserName：" + maintUserName);
        logger.debug("wStatus：" + wStatus);
        logger.debug("pageIndex" + pageIndex);
        logger.debug("pageNum" + pageNum);
        logger.debug("isFocus" + isFocus);

        Page page = new Page();
        if (!StringUtils.isBlank(pageIndex)) {
            page.setCurrentPage(Long.parseLong(pageIndex.toString()));
        }
        if (!StringUtils.isBlank(pageNum)) {
            page.setEveryPage(Long.parseLong(pageNum.toString()));
        }
        try {

            Map<String, Object> map = new HashMap<>();
            map.put("startCreateTime", startCreateTime);
            map.put("endCreateTime", endCreateTime);
            map.put("maintUserName", maintUserName);
            map.put("wstatus", wStatus);
            map.put("isFocus", isFocus);
            map.put("state", ConstDefine.STATE_ABLE);
            map.put("beginIndex", page.getBeginIndex());
            map.put("endinIndex", page.getEndinIndex());

            List<WorkOrderModel> WorkOrderModels = workOrderService.getAllWorkOrderListByPage(map, page);
            page.setList(WorkOrderModels);

            return new JsonResponseData(true,
                    StatusDefineMessage.GetMessage(StatusDefine.SUCCESS), StatusDefine.SUCCESS, "", page).toString();
        } catch (DataAccessException e) {
            logger.error(
                    "controller:WorkOrderController. function:getAllWorkOrderListByPage...msg:Get WorkOrder List By Page DataAccessException. error:"
                            + e.getMessage());
            logger.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DB_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.DB_ERROR), page).toString();
        } catch (Exception e) {
            logger.error(
                    "controller:WorkOrderController. function:getAllWorkOrderListByPage...msg:Get WorkOrder List By Page Exception. error:"
                            + e.getMessage());
            logger.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.SYS_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.SYS_ERROR), page).toString();
        }
    }

    /**
     * 新增运维工单信息
     * HTTP 方式：POST
     * API 路径：/api/workOrder/workOrder
     * 方法名：addWorkOrder
     * 方法返回类型：String
     *
     * @Author: psl
     * @Date: 2019-06-03
     */
    @RequiresPermissions("YWGDCZ")
    @ApiOperation(value = "新增运维工单信息", httpMethod = "POST", response = String.class, notes = "新增运维工单信息，提供运维工单管理-创建工单使用")
    @RequestMapping(value = "/api/workOrder/workOrder", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody
    String addWorkOrder(@RequestBody @Validated WorkOrderAddVO WorkOrderAddVO, BindingResult result) {

        logger.debug("Request RESTful API:addWorkOrder");
        logger.debug("WorkOrderAddVO：" + WorkOrderAddVO);

        try {
            if (result.hasErrors()) {
                return JsonResponseData.ofMessage(StatusDefine.DATA_FORMAT_ERROR, result.getFieldError().getDefaultMessage());
            }
            int ret = workOrderService.addWorkOrder(WorkOrderAddVO);

            if (ret > 0) {
                return new JsonResponseData(true,
                        StatusDefineMessage.GetMessage(StatusDefine.SUCCESS), StatusDefine.SUCCESS, "", ret).toString();
            } else {
                return new JsonResponseData(false,
                        "", StatusDefine.FAILURE, StatusDefineMessage.GetMessage(StatusDefine.FAILURE), "").toString();
            }
        } catch (DataAccessException e) {
            logger.error(
                    "controller:WorkOrderController. function:addWorkOrder...msg:Add WorkOrder DataAccessException. error:"
                            + e.getMessage());
            logger.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DB_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.DB_ERROR), null).toString();
        } catch (Exception e) {
            logger.error(
                    "controller:WorkOrderController. function:addWorkOrder...msg:Add WorkOrder Exception. error:"
                            + e.getMessage());
            logger.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.SYS_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.SYS_ERROR), null).toString();
        }
    }

    /**
     * 维修设备列表
     * HTTP 方式：GET
     * API 路径：/api/repairCamera
     * 方法名：getRepairCamera
     * 方法返回类型：String
     *
     * @Author: zhouhao
     * @Date: 2019-06-10
     */
    @ApiOperation(value = "维修设备列表", httpMethod = "GET", response = String.class, notes = "维修设备列表，提供运维工单管理-创建工单使用")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "maintUser", value = "运维人员ID",  paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "caName", value = "设备名称",  paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "exception", value = "异常类型",  paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "group", value = "分组",  paramType = "query", dataType = "String")
    })
    @RequestMapping(value = "/api/workOrder/repairCamera", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String getRepairCamera(Integer maintUser,String caName,String exception,String group) {

        log.debug("Request RESTful API:getRepairCamera");
        log.debug("caNumber：" + maintUser);
        log.debug("caName：" + caName);
        log.debug("exception：" + exception);
        log.debug("group：" + group);
        try{
            List<WorkRepairCameraVO> list=repairCameraService.getRepairCamera(maintUser,caName,exception,group);
            return JsonResponseData.ofSuccess(list);
        }catch (DataValidationException e) {
            log.error(
                    "controller:WorkOrderController. function:getRepairCamera...msg: getRepairCamera DataValidationException");
            log.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DATA_FORMAT_ERROR,
                    e.getMessage(), null).toString();
        }catch (DataAccessException e) {
            log.error(
                    "controller:WorkOrderController. function:getRepairCamera...msg:getRepairCamera DataAccessException. error:"
                            + e.getMessage());
            log.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DB_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.DB_ERROR), null).toString();
        } catch (Exception e) {
            e.printStackTrace();
            log.error(
                    "controller:WorkOrderController. function:getRepairCamera...msg:getRepairCamera Exception. error:"
                            + e.getMessage());
            log.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.SYS_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.SYS_ERROR), null).toString();
        }
    }

    /**
     * 运维人员列表
     * HTTP 方式：GET
     * API 路径：/api/workOrder/operationUser
     * 方法名：getOperationUser
     * 方法返回类型：String
     *
     * @Author: zhouhao
     * @Date: 2019-06-10
     */
    @ApiOperation(value = "运维人员列表", httpMethod = "GET", response = String.class, notes = "运维人员列表，提供运维工单管理-创建工单使用")
    @RequestMapping(value = "/api/workOrder/operationUser", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String getOperationUser() {

        try{
            List<User> list=userService.selectUserByApp();
            return JsonResponseData.ofSuccess(list);
        }catch (DataValidationException e) {
            log.error(
                    "controller:WorkOrderController. function:getOperationUser...msg: getOperationUser DataValidationException");
            log.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DATA_FORMAT_ERROR,
                    e.getMessage(), null).toString();
        }catch (DataAccessException e) {
            log.error(
                    "controller:WorkOrderController. function:getOperationUser...msg:getOperationUser DataAccessException. error:"
                            + e.getMessage());
            log.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DB_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.DB_ERROR), null).toString();
        } catch (Exception e) {
            log.error(
                    "controller:WorkOrderController. function:getOperationUser...msg:getOperationUser Exception. error:"
                            + e.getMessage());
            log.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.SYS_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.SYS_ERROR), null).toString();
        }
    }

    /**
     * 运维工单详情
     * HTTP 方式：GET
     * API 路径：/api/workOrder/getWorkOrderInfo
     * 方法名：getWorkOrderInfo
     * 方法返回类型：String
     *
     * @Author: zhouhao
     * @Date: 2019-06-10
     */
    @RequiresPermissions("YWGDFW")
    @ApiOperation(value = "运维工单详情", httpMethod = "GET", response = String.class, notes = "运维工单详情，提供运维工单管理使用")
    @RequestMapping(value = "/api/workOrder/getWorkOrderInfo", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String getWorkOrderInfo(Integer orderId) {

        try{
            WorkOrderInfo workOrderInfo =repairCameraService.getWorkOrderInfo(orderId);
            return JsonResponseData.ofSuccess(workOrderInfo);
        }catch (DataValidationException e) {
            log.error(
                    "controller:WorkOrderController. function:getWorkOrderInfo...msg: getWorkOrderInfo DataValidationException");
            log.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DATA_FORMAT_ERROR,
                    e.getMessage(), null).toString();
        }catch (DataAccessException e) {
            log.error(
                    "controller:WorkOrderController. function:getWorkOrderInfo...msg:getWorkOrderInfo DataAccessException. error:"
                            + e.getMessage());
            log.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DB_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.DB_ERROR), null).toString();
        } catch (Exception e) {
            log.error(
                    "controller:WorkOrderController. function:getWorkOrderInfo...msg:getWorkOrderInfo Exception. error:"
                            + e.getMessage());
            log.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.SYS_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.SYS_ERROR), null).toString();
        }
    }


    /**
     * 修改运维工单状态
     * HTTP 方式：GET
     * API 路径：/api/workOrder/upWorkOderState
     * 方法名：upWorkOderState
     * 方法返回类型：String
     *
     * @Author: zhouhao
     * @Date: 2019-06-10
     */
    @RequiresPermissions("YWGDCZ")
    @ApiOperation(value = "修改运维工单状态", httpMethod = "PUT", response = String.class, notes = "修改运维工单状态，提供运维工单使用")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderId", value = "工单ID",  paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "orderState", value =  "操作状态  1改派 2接单 3退回 4 待确认 5 未通过  6 完成" ,  paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "logDescribe", value = "原因描述,改派、未通过的时候传入",  paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "finishTime", value = "要求完成时间,改派的时候传入",  paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "geneUserId", value = "运维人员",  paramType = "query", dataType = "int")
    })
    @RequestMapping(value = "/api/workOrder/upWorkOderState", method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String upWorkOderState(Integer orderId,Integer orderState,String logDescribe,String finishTime,Integer geneUserId) {

        log.debug("Request RESTful API:getRepairCamera");
        log.debug("orderId：" + orderId);
        log.debug("orderState：" + orderState);
        log.debug("logDescribe：" + logDescribe);
        log.debug("finishTime：" + finishTime);
        log.debug("geneUserId：" + geneUserId);
        try{
            if(orderState == DisposeTypeEnum.REASSIGNMENT.getEn()){
                if(StringUtils.isBlank(finishTime)){
                    throw new DataValidationException("要求完成时间不能为空");
                }
            }
            if(geneUserId == null){
                throw new DataValidationException("运维人员不能为空");
            }
            if(repairCameraService.upWorkOderstate(orderId,orderState,geneUserId,logDescribe,finishTime)){
                return JsonResponseData.ofSuccess(null);
            }
            return JsonResponseData.ofFailure();
        }catch (SystemException e) {
            log.error(
                    "controller:WorkOrderController. function:upWorkOderState...msg: upWorkOderState SystemException");
            log.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DATA_FORMAT_ERROR,
                    e.getMessage(), null).toString();
        }catch (DataValidationException e) {
            log.error(
                    "controller:WorkOrderController. function:upWorkOderState...msg: upWorkOderState DataValidationException");
            log.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DATA_FORMAT_ERROR,
                    e.getMessage(), null).toString();
        }catch (DataAccessException e) {
            e.printStackTrace();
            log.error(
                    "controller:WorkOrderController. function:upWorkOderState...msg:upWorkOderState DataAccessException. error:"
                            + e.getMessage());
            log.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DB_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.DB_ERROR), null).toString();
        } catch (Exception e) {
            log.error(
                    "controller:WorkOrderController. function:upWorkOderState...msg:upWorkOderState Exception. error:"
                            + e.getMessage());
            log.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.SYS_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.SYS_ERROR), null).toString();
        }
    }

    /**
     * 添加工单关注
     * HTTP 方式：GET
     * API 路径：/api/workOrder/addFocus
     * 方法名：addFocus
     * 方法返回类型：String
     *
     * @Author: zhouhao
     * @Date: 2019-06-10
     */
    @ApiOperation(value = "添加工单关注", httpMethod = "GET", response = String.class, notes = "添加工单关注，提供运维工单PC使用")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderId", value = "工单ID",  paramType = "query", dataType = "int")
    })
    @RequestMapping(value = "/api/workOrder/addFocus", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String addFocus(Integer orderId) {

        try{
            if(repairCameraService.addFocus(orderId)){
                return JsonResponseData.ofSuccess(null);
            }
            return JsonResponseData.ofFailure();
        }catch (DataValidationException e) {
            log.error(
                    "controller:WorkOrderController. function:addFocus...msg: addFocus DataValidationException");
            log.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DATA_FORMAT_ERROR,
                    e.getMessage(), null).toString();
        }catch (DataAccessException e) {
            log.error(
                    "controller:WorkOrderController. function:addFocus...msg:addFocus DataAccessException. error:"
                            + e.getMessage());
            log.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DB_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.DB_ERROR), null).toString();
        } catch (Exception e) {
            log.error(
                    "controller:WorkOrderController. function:addFocus...msg:addFocus Exception. error:"
                            + e.getMessage());
            log.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.SYS_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.SYS_ERROR), null).toString();
        }
    }

    /**
     * 取消工单关注
     * HTTP 方式：GET
     * API 路径：/api/workOrder/delFocus
     * 方法名：addFocus
     * 方法返回类型：String
     *
     * @Author: zhouhao
     * @Date: 2019-06-10
     */
    @ApiOperation(value = "取消工单关注", httpMethod = "DELETE", response = String.class, notes = "取消工单关注，提供运维工单PC使用")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderId", value = "工单ID",  paramType = "query", dataType = "int")
    })
    @RequestMapping(value = "/api/workOrder/delFocus", method = RequestMethod.DELETE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String delFocus(Integer orderId) {

        try{
            if(repairCameraService.delFocus(orderId)){
                return JsonResponseData.ofSuccess(null);
            }
            return JsonResponseData.ofFailure();
        }catch (DataValidationException e) {
            log.error(
                    "controller:WorkOrderController. function:delFocus...msg: delFocus DataValidationException");
            log.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DATA_FORMAT_ERROR,
                    e.getMessage(), null).toString();
        }catch (DataAccessException e) {
            log.error(
                    "controller:WorkOrderController. function:delFocus...msg:delFocus DataAccessException. error:"
                            + e.getMessage());
            log.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DB_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.DB_ERROR), null).toString();
        } catch (Exception e) {
            log.error(
                    "controller:WorkOrderController. function:delFocus...msg:delFocus Exception. error:"
                            + e.getMessage());
            log.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.SYS_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.SYS_ERROR), null).toString();
        }
    }


    /**
     * 工单撤回
     * HTTP 方式：GET
     * API 路径：/api/workOrder/delWorkOrder
     * 方法名：addFocus
     * 方法返回类型：String
     *
     * @Author: zhouhao
     * @Date: 2019-06-10
     */
    @RequiresPermissions("YWGDCZ")
    @ApiOperation(value = "工单撤回", httpMethod = "DELETE", response = String.class, notes = "工单撤回，提供运维工单PC使用")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderId", value = "工单ID",  paramType = "query", dataType = "int")
    })
    @RequestMapping(value = "/api/workOrder/delWorkOrder", method = RequestMethod.DELETE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String delWorkOrder(Integer orderId) {

        try{
            if(repairCameraService.delWorkOrder(orderId)){
                return JsonResponseData.ofSuccess(null);
            }
            return JsonResponseData.ofFailure();
        }catch (SystemException e) {
            log.error(
                    "controller:WorkOrderController. function:delWorkOrder...msg: delWorkOrder SystemException");
            log.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DATA_FORMAT_ERROR,
                    e.getMessage(), null).toString();
        }catch (DataValidationException e) {
            log.error(
                    "controller:WorkOrderController. function:delWorkOrder...msg: delWorkOrder DataValidationException");
            log.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DATA_FORMAT_ERROR,
                    e.getMessage(), null).toString();
        }catch (DataAccessException e) {
            log.error(
                    "controller:WorkOrderController. function:delWorkOrder...msg:delWorkOrder DataAccessException. error:"
                            + e.getMessage());
            log.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DB_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.DB_ERROR), null).toString();
        } catch (Exception e) {
            log.error(
                    "controller:WorkOrderController. function:delWorkOrder...msg:delWorkOrder Exception. error:"
                            + e.getMessage());
            log.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.SYS_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.SYS_ERROR), null).toString();
        }
    }


}
